/*============================================================================
 PROJECT: DealHits
 FILE:    PhotoGalleryView.m
 AUTHOR:  Khoai Nguyen Minh
 DATE:    9/19/13
 =============================================================================*/

/*============================================================================
 IMPORT
 =============================================================================*/
#import "PhotoGalleryView.h"
#import "AssetLibraryHelper.h"
#import "FFCircularProgressView.h"
#import "FileRequestQueueManager.h"

/*============================================================================
 PRIVATE MACRO
 =============================================================================*/
/*============================================================================
 PRIVATE INTERFACE
 =============================================================================*/
@interface PhotoGalleryView()

- (IBAction)didTouchedOnButton:(id)sender;
- (IBAction)didTouchedOnSeletectButton:(id)sender;

@property (strong, nonatomic) FFCircularProgressView *cicleProgressView;
@property (strong, nonatomic) UIView *overlayView;
@property (strong, nonatomic) FileRequestBlock requestBlock;

@end

@implementation PhotoGalleryView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.userInteractionEnabled = YES;
    self.layer.cornerRadius = kCornerRadius;
    self.layer.masksToBounds = YES;
    self.clipsToBounds = YES;
    
    LayerBorderWithSizeColor(self.layer, 1, UIColorFromRGB(0xb8b8b8));
    self.selectButton.hidden = YES;
    
    /* add overlay view */
    self.overlayView = [[UIView alloc] init];
    self.overlayView.backgroundColor = [UIColor blackColor];
    self.overlayView.alpha = 0.4;
    [self addSubview:self.overlayView];
    
    /* add cicle progress view here */
    self.cicleProgressView = [[FFCircularProgressView alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    self.cicleProgressView.progressType = kProgressTypeUpload;
    self.cicleProgressView.hidden = YES;
    [self addSubview:self.cicleProgressView];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.cicleProgressView.center = self.center;
    self.overlayView.frame = self.bounds;
}

- (void)showProgressStatus:(BOOL)status {
    self.cicleProgressView.hidden = !status;
    self.selectButton.hidden = status;
    self.overlayView.hidden = !status;
}

- (void)setRequest:(FileRequest *)request {
    _request = request;
    
    /* load default cover image */
    _photoImageView.image = [[IBHelper sharedUIHelper] loadImage:@"default_place"];
    if(self.request.url.length > 0) {
        if([self.request.url hasPrefix:kAssetURLFormat]) {
            
            FileRequestQueueManager *manager = [FileRequestQueueManager sharedManager];
            [self showProgressStatus:YES];
            
            if([manager isUploadingFileRequest:self.request]) {
                [self.cicleProgressView startSpinProgressBackgroundLayer];
            }
            
            /* create request file block */
            if(!self.requestBlock) {
                __weak PhotoGalleryView *weakSelf = self;
                self.requestBlock = ^(FileRequest *fileRequest, CGFloat percentage, NSError *error) {
                    if([fileRequest.identifier isEqualToString:weakSelf.request.identifier]) {
                        if(percentage > 0 && percentage < 1) {
                            weakSelf.cicleProgressView.progress = percentage;
                            
                            if(weakSelf.cicleProgressView.isSpinning) {
                                [weakSelf.cicleProgressView stopSpinProgressBackgroundLayer];
                            }
                        } else if (percentage == 1 || error) {
                            weakSelf.cicleProgressView.hidden = YES;
                            [weakSelf showProgressStatus:NO];
                        }
                    }
                };
            }
            
            /* add photo into upload queue */
            [manager uploadFile:self.request usingBlock:self.requestBlock];
            
            [self.photoImageView startLoading];
            [[AssetLibraryHelper sharedPhotoLibraryAccessor] getAssestByURL:self.request.url
                                                                resultBlock:^(ALAsset *asset, NSError *error) {
                                                                    _photoImageView.image = [asset thumbnailImage];
                                                                    [self.photoImageView stopLoading];
                                                                }];
        } else {
            [self showProgressStatus:NO];
            
            __weak PhotoGalleryView *weakSelf = self;
            [self.photoImageView startLoading];
            [_photoImageView setImageWithURLString:self.request.url
                                  placeholderImage:[[IBHelper sharedUIHelper] loadCommonImage:@"default_place"]
                                           success:^(UIImage *image) {
                                               weakSelf.photoImageView.image = image;
                                               [weakSelf.photoImageView stopLoading];
                                           }
                                           failure:^(NSError *error) {
                                               [weakSelf.photoImageView stopLoading];
                                           }];
        }
    }}

- (IBAction)didTouchedOnButton:(id)sender {
    if(_viewPhotoBlock != NULL) {
        _viewPhotoBlock(self);
    }
}

- (IBAction)didTouchedOnSeletectButton:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    if(_selectPhotoBlock != NULL) {
        _selectPhotoBlock(self);
    }
}

@end
